package com.it.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.it.entity.*;
import com.it.exception.CommonException;
import com.it.mapper.*;
import com.it.service.HobbyService;
import com.it.service.LogService;
import com.it.service.UserService;
import com.it.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：〈用户接口/控制器〉用户相关的请求都在这里
 */
@RequestMapping("/user")
@Controller
public class UserController {
    @Resource
    private UserIntegralReduceMapper userIntegralReduceMapper;
    @Resource
    private UserHobbyMappper userHobbyMappper;
    @Autowired
    private UserService userService;
    @Resource
    private GiftMapper giftMapper;
    @Autowired
    private ItdragonUtils itdragonUtils;
    @Resource
    private UserIntegralDao userIntegralDao;
    @Autowired
    private HobbyService hobbyService;
    @Resource
    private HobbyMapper hobbyMapper;
    private static final transient Logger log = LoggerFactory.getLogger(UserController.class);


    @ResponseBody
    @PostMapping(value = "/t01")
    public User test(@RequestBody List<User> user) {
        user.forEach(System.out::println);
        return new User();
    }


    /**
     * 抽奖 增加个人积分
     */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @GetMapping("/LuckyDraw.do")
    public ResultResponse LuckyDraw() {
        try {
            User sessionUser = itdragonUtils.getSessionUser();
            int residueDegree = sessionUser.getResidueDegree();
            String realName = sessionUser.getRealName();
            if (realName == null && realName.isEmpty()) {
                return Result.resuleError("需设置爱好，请继续完善资料");
            }
            String birthDate = sessionUser.getBirthDate();
            if (birthDate == null && birthDate.isEmpty()) {
                return Result.resuleError("需设置生日，请继续完善资料");
            }
            String imgUrl = sessionUser.getImgUrl();
            if (imgUrl == null && imgUrl.isEmpty()) {
                return Result.resuleError("需设置头像，请继续完善资料");
            }
            int i = hobbyService.selectCountForUserHobbies(sessionUser);
            if (i < 2) {
                return Result.resuleError("需设置至少两个爱好，请继续完善资料");
            }
            if (residueDegree > 0) {
                int num = NewRandom.returnIntegral();
                int integral = sessionUser.getIntegral();
                integral += num;
                sessionUser.setIntegral(integral);
                sessionUser.setResidueDegree(--residueDegree);
                boolean b = userService.updateByPrimaryKey(sessionUser);
                String currentTime = DateUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");
                UserIntegral userIntegral = new UserIntegral();
                userIntegral.setIntegral(num);
                userIntegral.setAcquiredate(currentTime);
                userIntegral.setUid(sessionUser.getId());
                Integer insert = userIntegralDao.insert(userIntegral);
                if (insert > 0) {
                    log.info("添加抽奖记录成功。");
                }
                if (b == false) {
                    return Result.resuleError("积分添加失败");
                }
//                int i = 1 / 0;
                return Result.resuleSuccess("您获得了 " + num +
                        " 积分，目前积分数为 " + integral +
                        " 分，您还可抽 " + residueDegree +
                        " 次");
            }
            return Result.resuleError("你已经用完了本日抽奖次数，请明日再来");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，抽不了");
        }
    }

    /**
     * 买空气
     */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @PostMapping("/Shopping.do")
    public ResultResponse Shopping(String id) {
        try {
            if (id == null || id == "") {
                return Result.resuleError("请选择商品");
            }
            Gift gift = giftMapper.selectById(id);
            Integer num = gift.getNum();
            if (gift == null) {
                return Result.resuleError("没有该礼品");
            } else if (num == 0) {
                return Result.resuleError("该礼品已经兑换完了，无法购买");
            }
            gift.setNum(--num);
            Integer integer = giftMapper.updateById(gift);
            User sessionUser = itdragonUtils.getSessionUser();
            ResultResponse resultResponse = userService.updateUserIntegral(sessionUser);
            UserIntegralReduce userIntegralReduce = new UserIntegralReduce();
            userIntegralReduce.setUid(sessionUser.getId());
            userIntegralReduce.setShoppingtime(DateUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            Integer insert = userIntegralReduceMapper.insert(userIntegralReduce);
//            int i = 1 / 0;
            if (resultResponse.getCode() == 200 && integer > 0 && insert > 0) {
                return Result.resuleSuccess("购买完成");
            }
            return Result.resuleError("购买失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，买不了");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @PostMapping(value = "/addMyHobbies.do")
    public ResultResponse addMyHobbies(Hobby hobby) {
        try {
            User sessionUser = itdragonUtils.getSessionUser();
            int hobbiesCount = hobbyService.selectCountForUserHobbies(sessionUser);
            if (hobbiesCount == 20) {
                return Result.resuleError("您的爱好数不能超过20个，您不能再继续设置爱好了");
            }
            List<Hobby> hobbies = hobbyMapper.selectHobbies(sessionUser.getId());
            ArrayList<String> nameList = new ArrayList<>();
            for (Hobby hobby1 : hobbies) {
                nameList.add(hobby1.getName());
            }
            if (nameList.contains(hobby.getName())) {
                return Result.resuleError("你已经设置过该爱好了");
            }
            //a变量用于判断所有用户设置的爱好名中是否已经存在了本次请求想要设置的爱好名
            Boolean a = false;
            EntityWrapper<Hobby> hobbyEntityWrapper = new EntityWrapper<>();
            List<Hobby> allHobbiesList = hobbyMapper.selectList(hobbyEntityWrapper);
            ArrayList<String> nameListForAll = new ArrayList<>();
            for (Hobby hobby1 : allHobbiesList) {
                nameListForAll.add(hobby1.getName());
            }
            if (!nameListForAll.contains(hobby.getName())) {
                a = hobbyService.insertHobby(hobby);
            } else if (nameListForAll.contains(hobby.getName())) {
                a = true;
            }
            //带id的完整爱好实体
            Hobby hobby1 = hobbyMapper.selectOne(hobby);
            boolean b = hobbyService.insertHobbyToAllHobbies(sessionUser, hobby1);
            if (a == true && b == true) {
                return Result.resuleSuccess("你已经成功设置此爱好了");
            }
            return Result.resuleSuccess("设置爱好失败了");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，无法设置爱好");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @DeleteMapping("/deleteMyHobbies.do")
    public ResultResponse deleteMyHobbies(UserHobby userHobby) {
        try {
            if (userHobby.getId() == null) {
                return Result.resuleError("请选择爱好");
            }
            User sessionUser = itdragonUtils.getSessionUser();
            userHobby.setUserId(sessionUser.getId());
            if (userHobbyMappper.selectOne(userHobby) == null) {
                return Result.resuleError("无此爱好，无需删除");
            }
            boolean b = hobbyService.deleteMyHobbies(userHobby.getId(), sessionUser.getId());
            if (b) {
                return Result.resuleSuccess("删除成功");
            }
            return Result.resuleError("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，无法删除爱好");
        }
    }

    /**
     * @description:获取个人信息
     * @author: txf
     * @date: 2022/7/28 14:50
     */

    @ResponseBody
    @GetMapping("/getInformation.do")
    public User getInformation() {
        User sessionUser = itdragonUtils.getSessionUser();
        User myInformation = userService.getMyInformation(sessionUser);
        return myInformation;
    }

    /**
     * 修改头像
     *
     * @param user
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @PutMapping("/upadateImg.do")
    public ResultResponse editUserImg(User user) {
        try {
            User sessionUser = itdragonUtils.getSessionUser();
            if (!user.getId().equals(sessionUser.getId())) {
                return Result.resuleError("你只能修改自己的账户");
            }
            if (user.getImgUrl() == null || user.getImgUrl().isEmpty()) {
                return Result.resuleError("修改头像失败,未知错误");
            }
            if (user.getId() == null || user.getId().isEmpty()) {
                return Result.resuleError("修改头像失败,未知错误");
            }
            User UserUser = new User();
            UserUser.setImgUrl(user.getImgUrl());
            UserUser.setId(user.getId());
            UserUser.setIntegral(sessionUser.getIntegral());
            UserUser.setResidueDegree(sessionUser.getResidueDegree());
            boolean result = userService.updateByPrimaryKey(UserUser);
            if (!result) {
                return Result.resuleError("修改头像失败,未知错误");
            }
            return Result.resuleSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，无法修改图片");
        }
    }

    /**
     * @description:
     * @author: txf
     * @date: 2022/7/29 14:27
     */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @PutMapping("/user.do")
    public ResultResponse editUser(User user) {
        try {
            User sessionUser = itdragonUtils.getSessionUser();
            if (!user.getId().equals(sessionUser.getId())) {
                return Result.resuleError("你只能修改自己的账户");
            }


            boolean pwdBoolean = (user.getPassword() != null && sessionUser.getPassword().equals(user.getPassword())) || user.getPassword() == null;
            boolean emailBoolean = (user.getEmail() != null && user.getEmail().equals(sessionUser.getEmail())) || user.getEmail() == null;
            boolean phoneNumBoolean = (user.getPhoneNum() != null && user.getPhoneNum().equals(sessionUser.getPhoneNum())) || user.getPhoneNum() == null;
            boolean typeBoolean = (user.getType() != null && user.getType().equals(sessionUser.getType())) || user.getType() == null;

            if (!(pwdBoolean && emailBoolean && phoneNumBoolean && typeBoolean)) {
                return Result.resuleError("你不能修改敏感数据");
            }
            user.setIntegral(sessionUser.getIntegral());
            user.setResidueDegree(sessionUser.getResidueDegree());
            boolean result = userService.updateByPrimaryKey(user);
            if (!result) {
                return Result.resuleError("修改个人信息失败");
            }
            return Result.resuleSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(500, "系统繁忙，无法修改个人信息");
        }
    }

}